require(["config"],function(){
    require(["jquery","template","swiper","header","cookie"],($,template,Swiper)=>{
        
        function Detail(){
            this.init();
           this.img=null;
        }
        $.extend(Detail.prototype,{
            init(){
                this.render();
            },
            render(){
                //art-template
                $.getJSON("http://rap2api.taobao.org/app/mock/116724/mi-detail",
                $.proxy(this.Rendertemplate,this))             
                    },
            //加载模板
            Rendertemplate(data){
           
            var html1 = template("template-detail",{data:data.arr});
            //  var html2 = template("template-left",{data:data.arr});
            $("#template-wrap").html(html1);

            //   $(".left").html(html2);
            
                this.addListener();
            } ,
           
            //注册购物事件监听
            addListener(){
                var $quantity= $("#quantity");
                var quantityText= Number($quantity.text());
                $("#decr").click(()=>{
                    if(quantityText > 1){
                        quantityText -= 1;
                        $quantity.text(quantityText);
                    }
                });
                $("#incr").click(()=>{
                    quantityText += 1;
                    $quantity.text(quantityText);
                });
               
                $("main").delegate(".add-cart","click",$.proxy(this.addCookie,this));
                $("main").delegate(".buy","click",$.proxy(this.addCookie,this));
                $(".buy").click(()=>{
               location.href = "/html/cart.html";
            })
        },
        //保存cookie
        addCookie(){
            $.cookie.json=true;
                    var products = $.cookie("products") ||[];
                    var url = new URL(window.location);
                    const id = url.searchParams.get('id') ;
                    var product={
                        id:id,
                        img:this.img,
                        price:$("#price").text(),
                        title:$("#title").text(),
                        quantity:$("#quantity").text()
                    }
                    //查询
                    var has = products.some(function(ele){
                        if(ele.id ==product.id){//已有选购商品
                            ele.quantity =product.quantity;
                            return true;
                        }
                        return false;
                        })
                    if(!has){
                        products.push(product);
                    }
                 
                    $.cookie("products",products,{expires:3,path:"/"});
        }
        })
        new Detail();
    });
});